﻿/*
 * Creato da SharpDevelop.
 * Utente: Ciccio
 * Data: 26/04/2008
 * Ora: 18.35
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */

using System.Web.Security;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Collections.Generic;
using System;
using System.Data;
using MySql.Data.MySqlClient;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using System.Globalization;
using System.Security.Cryptography;
using System.Text;
using System.Web.Configuration;
using System.Web.Management;
using ACM.cmsarea08;

namespace ACM.cmsarea08.Provider
{
	/// <summary>
	/// Description of Class1.
	/// </summary>
	public sealed class Itan_StatusProvider : BufferedWebEventProvider 
	{
		string path = "public/log.txt";
		
        #region Implementation
        //Inizializza il Provider
        public override void Initialize(string name, NameValueCollection configuration)
        {
        	path = WebBaseEvent.ApplicationInformation.ApplicationPath + "/public/log.txt";
            base.Initialize(name, configuration);
            //this.AddToLog("AVVIO PROVIDER: "+ DateTime.Now + "\n");
        }
		
        private void AddToLog(string msg) {
        	
        	using (System.IO.StreamWriter sw = new System.IO.StreamWriter(path,true)) {
        		sw.WriteLine(msg);
        	}
        }
        
        //Processa L'Evento
        public override void ProcessEvent(WebBaseEvent eventRaised)
        {

        	if (eventRaised is StatusEvent) {
	            if (base.UseBuffering)
	            {
	                base.ProcessEvent(eventRaised);
	            }
	            else
	            {
	            	//segui l'evento come se nulla fosse.
	            	List<WebBaseEvent> lista = new List<WebBaseEvent>();
	            	lista.Add(eventRaised);
	            	ProcessaTutto(lista);
	            }
        	}
        }
 
		//Processa gli eventi quando il buffer è pieno
        public override void ProcessEventFlush(WebEventBufferFlushInfo flushInfo)
	    {
        	
        	ProcessaTutto( flushInfo.Events);
        }

        //quando si chiude il provider:
        public override void Shutdown() {
        	Flush();
        }
 
        //pulizia degli eventi

        const string checkUrl  = "select id from {0}status where open='1' and url='{1}' and browser='{2}' and platform='{3}' and authenticated='{4}' and DATE_ADD(firstclick, INTERVAL 1 DAY) >Now() ;";
        const string insertUrl = "insert into {0}status (url, firstclick, lastclick, browser, platform, authenticated, clicks, open) VALUES(" +
        	" '{1}', Now(),Now(),'{2}','{3}', '{4}', 1,'1' " +
        	" );";
        const string updateUrl = "update {0}status set clicks = clicks+1 ,lastclick = Now() where id='{1}' limit 1; ";
        const string closeUrl = "update {0}status set open='0' where  open='1' and url='{1}' and browser='{2}' and platform='{3}' and authenticated='{4}' and DATE_ADD(firstclick, INTERVAL 1 DAY) <=Now();";
        
        private void ProcessaTutto(ICollection<WebBaseEvent> collection) {
        	
        	foreach (WebBaseEvent we in collection)
  			{
        		if(!(we is StatusEvent)) continue;
        		object cq = null;
        		string updId ="";
        		bool insert=false;
        		string cquery = string.Format(checkUrl, mainconfiguration.MainConf.PrefissoTabelle, 
        		                          ((StatusEvent)we).url,
        		                          ((StatusEvent)we).browser,
        		                          ((StatusEvent)we).so,
        		                          (((StatusEvent)we).isAuthenticated==true?"1":"0") );
        		//AddToLog("SONO QUI: "+ cquery);
        		cq = DBManager.mainConnection.HStandard_SC(cquery);
        		if(cq==null) {
        			insert=true;
        		} else {
        			if(cq is byte[]) updId = System.Text.Encoding.UTF8.GetString( (byte[]) cq);
        			else updId = cq.ToString();
        			if(updId.Trim()=="") 
        				insert=true;
        		}
        		if(insert) {
	        		string qq = string.Format(insertUrl,mainconfiguration.MainConf.PrefissoTabelle, 
	        		                          ((StatusEvent)we).url,
	        		                          ((StatusEvent)we).browser,
	        		                          ((StatusEvent)we).so,
	        		                          (((StatusEvent)we).isAuthenticated==true?"1":"0") );
        			//AddToLog("SONO QUI - INS : "+ qq);
	        		ACM.cmsarea08.DBManager.mainConnection.Helper_NonQuery(qq);
	        		qq = string.Format(closeUrl,mainconfiguration.MainConf.PrefissoTabelle, 
	        		                          ((StatusEvent)we).url,
	        		                          ((StatusEvent)we).browser,
	        		                          ((StatusEvent)we).so,
	        		                          (((StatusEvent)we).isAuthenticated==true?"1":"0") );
	        		ACM.cmsarea08.DBManager.mainConnection.Helper_NonQuery(qq);
        		} else {
 	        		string qq = string.Format(updateUrl,mainconfiguration.MainConf.PrefissoTabelle, 
	        		                          updId );
        			//AddToLog("SONO QUI - UPD : "+ qq);
	        		ACM.cmsarea08.DBManager.mainConnection.Helper_NonQuery(qq);       			
        		}
        	}
        }
        private void ProcessaTutto(WebBaseEventCollection collection) {
        	
        	foreach (WebBaseEvent we in collection)
  			{
        		if(!(we is StatusEvent)) continue;
        		object cq = null;
        		string updId ="";
        		bool insert=false;
        		string cquery = string.Format(checkUrl, mainconfiguration.MainConf.PrefissoTabelle, 
        		                          ((StatusEvent)we).url,
        		                          ((StatusEvent)we).browser,
        		                          ((StatusEvent)we).so,
        		                          (((StatusEvent)we).isAuthenticated==true?"1":"0") );
        		//AddToLog("SONO QUI: "+ cquery);
        		cq = DBManager.mainConnection.HStandard_SC(cquery);
        		if(cq==null) {
        			insert=true;
        		} else {
        			if(cq is byte[]) updId = System.Text.Encoding.UTF8.GetString( (byte[]) cq);
        			else updId = cq.ToString();
        			if(updId.Trim()=="") 
        				insert=true;
        		}
        		if(insert) {
	        		string qq = string.Format(insertUrl,mainconfiguration.MainConf.PrefissoTabelle, 
	        		                          ((StatusEvent)we).url,
	        		                          ((StatusEvent)we).browser,
	        		                          ((StatusEvent)we).so,
	        		                          (((StatusEvent)we).isAuthenticated==true?"1":"0") );
        			//AddToLog("SONO QUI - INS : "+ qq);
	        		ACM.cmsarea08.DBManager.mainConnection.Helper_NonQuery(qq);
	        		qq = string.Format(closeUrl,mainconfiguration.MainConf.PrefissoTabelle, 
	        		                          ((StatusEvent)we).url,
	        		                          ((StatusEvent)we).browser,
	        		                          ((StatusEvent)we).so,
	        		                          (((StatusEvent)we).isAuthenticated==true?"1":"0") );
	        		ACM.cmsarea08.DBManager.mainConnection.Helper_NonQuery(qq);
        		} else {
 	        		string qq = string.Format(updateUrl,mainconfiguration.MainConf.PrefissoTabelle, 
	        		                          updId );
        			//AddToLog("SONO QUI - UPD : "+ qq);
	        		ACM.cmsarea08.DBManager.mainConnection.Helper_NonQuery(qq);       			
        		}
        	}
        }

        #endregion
	}

	public class StatusEvent : WebAuditEvent
	{
	    public string url;
	    public string browser;
	    public string so;
	    public bool isAuthenticated;
	
	    
	    /* script check variabili http:
			int loop1, loop2;
			NameValueCollection coll;
			coll=Request.ServerVariables; 
			
			Response.Write("Browser: " + Request.Browser.Browser + " " + Request.Browser.Version +"<br/>");
			Response.Write("SO: " + Request.Browser.Platform  + "<br/>");
			Response.Write("url: " + Request.Url  + "<br/>");
			// Get names of all keys into a string array. 
			String[] arr1 = coll.AllKeys; 
			for (loop1 = 0; loop1 < arr1.Length; loop1++) 
			{
			   Response.Write("Key: " + arr1[loop1] + "<br>");
			   String[] arr2=coll.GetValues(arr1[loop1]);
			   for (loop2 = 0; loop2 < arr2.Length; loop2++) {
			      Response.Write("Value " + loop2 + ": " + Server.HtmlEncode(arr2[loop2]) + "<br>");
			   }
			}	
			Response.Write("<hr/><hr/>");
		*/	    

		public StatusEvent(string msg, object eventSource, int eventCode)
	        : base(msg, eventSource, eventCode)
	    {
	        // Obtain the HTTP Context and store authentication details
	        url = msg;
	        browser = HttpContext.Current.Request.Browser.Browser + " " + HttpContext.Current.Request.Browser.Version;
	        so = HttpContext.Current.Request.Browser.Platform;
	        isAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated;
	    }
	
	    public StatusEvent(string msg, object eventSource, int eventCode, 
	                           int eventDetailCode)
	            : base(msg, eventSource, eventCode, eventDetailCode)
	    {
	        // Obtain the HTTP Context and store authentication details
	        url = msg;
	        browser = HttpContext.Current.Request.Browser.Browser + " " + HttpContext.Current.Request.Browser.Version;
	        so = HttpContext.Current.Request.Browser.Platform;
	        isAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated;
	    }
	} 
}
